package com.github.pig.admin.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.github.pig.admin.model.dto.RoleDTO;
import com.github.pig.admin.model.entity.RoleBean;
import com.github.pig.admin.model.entity.SysDept;
import com.github.pig.admin.model.entity.SysRole;
import com.github.pig.admin.model.zhgl.building.CommunityBuilding;
import com.github.pig.admin.model.zhgl.building.CommunityBuildingTree;
import com.github.pig.admin.model.zhgl.community.CommunityInfo;
import com.github.pig.admin.model.zhgl.house.UnitHouseBean;
import com.github.pig.admin.service.sys.SysDeptService;
import com.github.pig.admin.service.sys.SysRoleMenuService;
import com.github.pig.admin.service.sys.SysRoleService;
import com.github.pig.admin.service.sys.SysUserService;
import com.github.pig.admin.util.AjaxJson;
import com.github.pig.common.constant.CommonConstant;
import com.github.pig.common.util.R;
import com.github.pig.common.vo.CommunityInfoBean;
import com.github.pig.common.vo.UserVO;
import com.github.pig.common.web.BaseController;
import com.netflix.discovery.converters.Auto;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import sun.util.resources.cldr.ebu.CurrencyNames_ebu;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author lengleng
 * @date 2017/11/5
 */
@RestController
@RequestMapping("/role")
public class RoleController extends BaseController {
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysRoleMenuService sysRoleMenuService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysDeptService deptService;

    /**
     * 通过ID查询角色信息
     *
     * @param id ID
     * @return 角色信息
     */
    @GetMapping("/{id}")
    public SysRole role(@PathVariable Integer id) {
        return sysRoleService.selectById(id);
    }


    /**
     * 添加角色
     *
     * @param roleDto 角色信息
     * @return success、false
     */
    @PostMapping
    public R<Boolean> role(@RequestBody RoleDTO roleDto) {
        R<Boolean> r = new R<>();
        if(sysRoleService.insertRole(roleDto)){
            r.setData(true);
        }else{
            r.setMsg("角色标识已存在！");
            r.setData(false);
        }
        return r;
    }


    /**
     * 修改角色
     *
     * @param roleDto 角色信息
     * @return success/false
     */
    @PutMapping
    public R<Boolean> roleUpdate(@RequestBody RoleDTO roleDto) {
        R<Boolean> r = new R<>();
        if(sysRoleService.updateRoleById(roleDto)) {
            r.setData(true);
        }
//        }else{
//            r.setMsg("角色标识已存在！");
//            r.setData(false);
//        }
        return r;
    }

    @DeleteMapping("/{id}")
    public R<Boolean> roleDel(@PathVariable Integer id) {
        SysRole sysRole = sysRoleService.selectById(id);
        sysRole.setDelFlag(CommonConstant.STATUS_DEL);
        return new R<>(sysRoleService.updateById(sysRole));
    }

    /**
     * 获取角色列表(根据当前登录用户所属部门获取到该部门下的角色)
     *
     * @param deptId  部门ID
     * @return 角色列表
     */
    @GetMapping("/roleList/{deptId}")
    public List<SysRole> roleList(@PathVariable Integer deptId) {
        return sysRoleService.selectListByDeptId(deptId);
    }

    /**
     * 分页查询角色信息(根据当前登录用户所属部门获取到子部门下所有角色列表)
     *
     * @return 分页对象
     */
    @RequestMapping("/rolePage")
    public Page rolePage(@RequestParam Map<String, Object> params,RoleBean bean) {
        EntityWrapper entityWrapper = new EntityWrapper<SysRole>();
        Page<SysRole> page = new Page<SysRole>(Integer.parseInt(params.getOrDefault("page", 1).toString())
                , Integer.parseInt(params.getOrDefault("limit", 10).toString()));
        if(StringUtils.isBlank(bean.getCommunityId())){
            return page;
        }
        // 获取到当前登录用户
        UserVO user = sysUserService.findUserByUsername(getUserName());
        if(!CommonConstant.MANAGE_NAME.equals(user.getUsername())) {
            bean.setIsManager( user.getCommunityList().stream().map(CommunityInfoBean :: getCommunityId ).collect(Collectors.joining(",")));
        }
        return sysRoleService.selectListByCurrentUser(page,bean);
    }

    /**
     * 更新角色菜单
     *
     * @param roleId  角色ID
     * @param menuIds 菜单结合
     * @return success、false
     */
    @PutMapping("/roleMenuUpd")
    public R<Boolean> roleMenuUpd(Integer roleId, @RequestParam("menuIds[]") Integer[] menuIds) {
        SysRole sysRole = sysRoleService.selectById(roleId);
        return new R<>(sysRoleMenuService.insertRoleMenus(sysRole.getRoleCode(), roleId, menuIds));
    }

    @RequestMapping("/getRoleNodeByParent")
    public List<CommunityBuildingTree> getDeptNodeByParent(SysDept bean) {
        EntityWrapper entityWrapper = new EntityWrapper<SysDept>();
        entityWrapper.eq(CommonConstant.DEL_FLAG,CommonConstant.STATUS_NORMAL);
        if(bean.getParentId()!=null&&StringUtils.isNotEmpty(bean.getParentId().toString())){
            entityWrapper.eq("parent_id",bean.getParentId());
        }
        UserVO user = sysUserService.findUserByUsername(getUserName());
        if(user==null){
            return null;
        }
        SysDept dept = deptService.selectById(user.getDeptId());
        if(dept!=null){
            entityWrapper.eq("company_id",dept.getCompanyId());
        }
        return sysRoleService.getDeptRoleByParent(entityWrapper,bean);
    }


    @RequestMapping("/getRoleByCommunityId")
    public List<SysRole> getRoleByCommunityId(String ids){
        EntityWrapper entityWrapper = new EntityWrapper();
        if(StringUtils.isEmpty(ids)){
            return null;
        }
        List<SysDept> depts = new ArrayList<>();
        for( String id : ids.split(",")){
            depts.addAll(deptService.getChildsByDeptId(id,null));
        }
        entityWrapper.in("community_id",depts.stream().map(SysDept::getDeptId).collect(Collectors.toList()));
        List<SysRole> list = sysRoleService.selectList(entityWrapper);
        return list;
    }

    @RequestMapping("/queryRole")
    public List<SysRole> queryRole(RoleBean bean) {
        return sysRoleService.selectListByCurrentUser(bean);
    }
}
